package quienesquien;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FilterClass implements Filter{
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
        HttpServletRequest request = (HttpServletRequest) req;  
        HttpServletResponse response = (HttpServletResponse) res;
        
        if (CheckCookie(request, response)) {
            chain.doFilter(req, res);
        } else {
            response.sendRedirect("login.jsp"); //TODO Cambiar por el nombre de la accion del login de la vista
        }
    }
    
    public void init(FilterConfig config) throws ServletException {
    }
    
    public void destroy() {
    }  
     
    //This method removes the cookies
    public static void removeAutoLogin(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(true);
        
        Cookie IdSesionCookie = new Cookie(session.getId(), "");
        IdSesionCookie.setPath("/");
        IdSesionCookie.setMaxAge(0);// delete this cookie

        response.addCookie(IdSesionCookie);
    }
    
    //This method sets the cookies
    public static void setAutoLogin(HttpServletRequest request, HttpServletResponse response){
        int autoLoginExpire = (60 * 60 * 24) * 2; // 2 dias
        Cookie [] cookies = request.getCookies();
        HttpSession session = request.getSession(true);
        
        for(int i = 0; i < cookies.length; i++){
            if(cookies[i].getName().equalsIgnoreCase(session.getId())){
                cookies[i].setMaxAge(autoLoginExpire);
                response.addCookie(cookies[i]);
                break;
            }else{    
                Cookie IdSesionCookie = new Cookie(session.getId(), "");
                IdSesionCookie.setMaxAge(autoLoginExpire);
                IdSesionCookie.setPath("/");
                response.addCookie(IdSesionCookie);
            }
        }
    }
    
    public static Boolean CheckCookie(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(true);
        Cookie [] cookies = request.getCookies();
        
        for(int i = 0; i < cookies.length; i++){
            if(cookies[i].getName().equalsIgnoreCase(session.getId())){
                return true;
            }
        }
        
        return false;
    }
}
 

  
